import axios from 'axios';
import Vue from 'vue';
import router from "@/router";
import {Message} from 'element-ui';
import store from "../store/store";

var vm = new Vue({
    router,
    store
});


export function fetch(options) {
    return new Promise((resolve, reject) => {
        const instance = axios.create({
            headers: {
                'Content-Type': 'application/json',
                'Access-Token': window.localStorage.getItem('token') ? window.localStorage.getItem('token') : ''
            }
        });
        instance(options)
            .then(response => {
                if (response.data.code == 200) {
                    let resStatus = (response.data.status + "").toUpperCase();
                    if (resStatus === "SUCCESS") { //只过滤返回服务器端状态为200的数据
                        resolve(response.data);
                        return true;
                    } else if (response.data.status === 'UNTOKEN') {
                        window.localStorage.removeItem('token');
                        Message.warning({
                            message: "登录失效，请重新登录！",
                            onClose: () => {
                                window.location.href = "/login";
                            }
                        });
                    } else if (response.data.status === 'UNLOGIN') {
                        window.localStorage.removeItem('token');
                        Message.warning({
                            message: "请选登录！",
                            onClose: () => {
                                window.location.href = "/login";
                            }
                        });
                    } else if (response.data.status === 'FAIL') {
                        Message.close()
                        Message.error(response.data.message);
                    } else {
                        Message.error(response.data.message);
                    }
                    return false;
                } else {
                    Message.error('服务器异常');
                    return false;
                }
            })
            .catch(err => {
                Message.error(err);
                reject(err);
            })
    });
}
